package com.gis.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.gis.bean.User;
import com.gis.dao.MessageDao;
import com.gis.dao.UserDao;
import com.gis.util.Constant;
import com.gis.util.MailContext;
import com.gis.util.ResponseUtil;
import com.gis.util.RestResponse;
import com.gis.util.MessageSender;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;

@WebServlet("/checkEmail")
public class CheckEmailServlet extends HttpServlet {
	UserDao userDao = new UserDao();
	MessageDao messageDao = new MessageDao();

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String email = req.getParameter("emailAddress");
		User user = userDao.getUser(username);
		if (user == null) {
			ResponseUtil.writeJson(resp, RestResponse.fail(Constant.USER_NOT_EXIST));
			return;
		}
		if (!StrUtil.equals(email, user.getEmail())) {
			ResponseUtil.writeJson(resp, RestResponse.fail(Constant.EMAIL_ERROR));
			return;
		}
		// 发送邮件
		String randomCode = UUID.randomUUID().toString();
		String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/";
		String url = basePath + "forgetPassword.jsp?username=" + username + "&randomCode=" + randomCode;
		String content = "请点击链接，重置密码<br/><a href='" + url + "'>" + url + "</a><br/>如无法打开，请复制链接并粘贴到浏览器的地址栏中打开";
		// 将其写入数据库 作为校验
		if(messageDao.selectByUsername(username) == null) {
			messageDao.addMessage(username, email, randomCode);
		} else {
			messageDao.updateMessage(username, email, randomCode);
		}
		MailContext mailContext = new MailContext(email, Constant.RESET_PASSWORD, content);
		MessageSender.send(mailContext);
		ResponseUtil.writeJson(resp, RestResponse.success("发送成功"));
	}
	
	

}
